import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class SocketService {
  private url = 'http://localhost:5000';
  private socket: SocketIOClient.Socket;
  private _observable: Observable<any>;

  constructor(private http: HttpClient) {
  }

  connect() {
    this.socket = io(this.url, {
      reconnectionAttempts: 5,
    }).connect();
    this._observable = new Observable(observer => {
      this.socket.on('message', data => {
        console.log(data);
        observer.next(data);
      });
      return () => {
        this.socket.disconnect();
      };
    });
  }

  sendMessage(msg) {
    this.socket.emit('message', msg);
  }

  getMessager() {

    return this._observable;
  }
}
